import React, { memo, useEffect, useCallback, useState } from 'react';
import { Modal, Form, Input, Select, Button, Space, message, ColorPicker, InputNumber } from 'antd';
import { BookOutlined, UserOutlined, DollarOutlined, ClockCircleOutlined } from '@ant-design/icons';
import type { ICourseFormProps } from '@/types/components/course';
import type { ICourseCreateRequest, ICourseUpdateRequest } from '@/types/course';
import { CourseStatusEnum } from '@/types/course';
import { validateCourseData } from '@/utils/validation';
import styles from './CourseForm.module.css';

const { Option } = Select;
const { TextArea } = Input;

/**
 * 课程表单组件
 * @description 用于创建和编辑课程信息的表单组件
 */
const CourseForm: React.FC<ICourseFormProps> = memo(({
  course,
  categories,
  visible,
  mode,
  onSubmit,
  onCancel,
  loading = false
}) => {
  const [form] = Form.useForm();
  const [selectedColor, setSelectedColor] = useState('#1890ff');

  // 表单初始化
  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && course) {
        // 编辑模式，填充现有数据
        form.setFieldsValue({
          name: course.name,
          courseCode: course.courseCode,
          teacher: course.teacher,
          description: course.description,
          color: course.color,
          categoryIds: course.categoryIds,
          duration: course.duration,
          fee: course.fee,
          capacity: course.capacity,
          status: course.status
        });
        setSelectedColor(course.color);
      } else {
        // 创建模式，重置表单
        form.resetFields();
        const defaultColor = '#1890ff';
        form.setFieldsValue({
          color: defaultColor,
          status: CourseStatusEnum.ACTIVE // 默认状态为正常
        });
        setSelectedColor(defaultColor);
      }
    }
  }, [visible, mode, course, form]);

  // 处理表单提交
  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      
      // 数据验证
      const validationResult = validateCourseData(values);
      if (!validationResult.isValid) {
        message.error(validationResult.message);
        return;
      }

      // 构造提交数据
      const submitData: ICourseCreateRequest | ICourseUpdateRequest = {
        name: values.name.trim(),
        courseCode: values.courseCode.trim(),
        teacher: values.teacher.trim(),
        description: values.description?.trim() || undefined,
        color: values.color,
        categoryIds: values.categoryIds || [],
        duration: values.duration || undefined,
        fee: values.fee || undefined,
        capacity: values.capacity || undefined,
        status: values.status
      };

      await onSubmit(submitData);
      form.resetFields();
    } catch (error) {
      console.error('表单提交失败:', error);
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  }, [form, onSubmit]);

  // 处理取消操作
  const handleCancel = useCallback(() => {
    form.resetFields();
    onCancel();
  }, [form, onCancel]);

  // 课程代码验证规则
  const validateCourseCode = useCallback(async (_: any, value: string) => {
    if (!value) {
      throw new Error('请输入课程代码');
    }
    if (value.length < 2) {
      throw new Error('课程代码长度不能少于2位');
    }
    if (!/^[A-Za-z0-9-_]+$/.test(value)) {
      throw new Error('课程代码只能包含字母、数字、横线和下划线');
    }
  }, []);

  // 处理颜色变化
  const handleColorChange = useCallback((color: any) => {
    const colorValue = typeof color === 'string' ? color : color.toHexString();
    setSelectedColor(colorValue);
    form.setFieldValue('color', colorValue);
  }, [form]);

  return (
    <Modal
      title={
        <div className={styles.modalTitle}>
          <BookOutlined className={styles.titleIcon} />
          {mode === 'create' ? '添加课程' : '编辑课程'}
        </div>
      }
      open={visible}
      onCancel={handleCancel}
      footer={
        <Space>
          <Button onClick={handleCancel}>
            取消
          </Button>
          <Button
            type="primary"
            loading={loading}
            onClick={handleSubmit}
          >
            {mode === 'create' ? '添加' : '保存'}
          </Button>
        </Space>
      }
      width={600}
      destroyOnHidden
      className={styles.courseFormModal}
    >
      <Form
        form={form}
        layout="vertical"
        className={styles.courseForm}
        autoComplete="off"
      >
        <div className={styles.formRow}>
          <Form.Item
            name="name"
            label="课程名称"
            rules={[
              { required: true, message: '请输入课程名称' },
              { min: 2, message: '课程名称长度不能少于2个字符' },
              { max: 100, message: '课程名称长度不能超过100个字符' }
            ]}
            className={styles.halfWidth}
          >
            <Input
              prefix={<BookOutlined />}
              placeholder="请输入课程名称"
              maxLength={100}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="courseCode"
            label="课程代码"
            rules={[
              { required: true, message: '请输入课程代码' },
              { validator: validateCourseCode }
            ]}
            className={styles.halfWidth}
          >
            <Input
              placeholder="请输入课程代码"
              maxLength={20}
              showCount
            />
          </Form.Item>
        </div>

        <div className={styles.formRow}>
          <Form.Item
            name="teacher"
            label="授课教师"
            rules={[
              { required: true, message: '请输入授课教师' },
              { min: 2, message: '教师姓名长度不能少于2个字符' },
              { max: 50, message: '教师姓名长度不能超过50个字符' }
            ]}
            className={styles.halfWidth}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入授课教师"
              maxLength={50}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="color"
            label="课程颜色"
            rules={[{ required: true, message: '请选择课程颜色' }]}
            className={styles.halfWidth}
          >
            <div className={styles.colorPickerWrapper}>
              <ColorPicker
                value={selectedColor}
                onChange={handleColorChange}
                showText
                format="hex"
                presets={[
                  {
                    label: '推荐颜色',
                    colors: [
                      '#1890ff', '#52c41a', '#faad14', '#f5222d',
                      '#722ed1', '#eb2f96', '#13c2c2', '#fa8c16'
                    ]
                  }
                ]}
              />
            </div>
          </Form.Item>
        </div>

        <Form.Item
          name="categoryIds"
          label="课程分类"
          rules={[{ required: true, message: '请选择课程分类' }]}
        >
          <Select
            mode="multiple"
            placeholder="请选择课程分类"
            allowClear
            maxTagCount="responsive"
          >
            {categories.map(category => (
              <Option key={category.id} value={category.id}>
                <div className={styles.categoryOption}>
                  <div 
                    className={styles.categoryColor}
                    style={{ backgroundColor: category.color }}
                  />
                  {category.name}
                </div>
              </Option>
            ))}
          </Select>
        </Form.Item>

        <div className={styles.formRow}>
          <Form.Item
            name="duration"
            label="课程时长（分钟）"
            className={styles.thirdWidth}
          >
            <InputNumber
              prefix={<ClockCircleOutlined />}
              placeholder="课程时长"
              min={15}
              max={480}
              step={15}
              className={styles.fullWidth}
            />
          </Form.Item>

          <Form.Item
            name="fee"
            label="课程费用（元）"
            className={styles.thirdWidth}
          >
            <InputNumber
              prefix={<DollarOutlined />}
              placeholder="课程费用"
              min={0}
              max={10000}
              step={10}
              precision={2}
              className={styles.fullWidth}
            />
          </Form.Item>

          <Form.Item
            name="capacity"
            label="课程容量（人）"
            className={styles.thirdWidth}
          >
            <InputNumber
              placeholder="课程容量"
              min={1}
              max={100}
              className={styles.fullWidth}
            />
          </Form.Item>
        </div>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Option value={CourseStatusEnum.ACTIVE}>正常</Option>
            <Option value={CourseStatusEnum.SUSPENDED}>暂停</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="description"
          label="课程描述"
        >
          <TextArea
            placeholder="请输入课程描述"
            rows={3}
            maxLength={500}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
});

CourseForm.displayName = 'CourseForm';

export default CourseForm;